package al.xc.wxsession.task;

import al.xc.common.util.SingleUtils;
import al.xc.common.util.TimeUtils;
import al.xc.service.IWechatAuthorService;
import al.xc.task.DelayService;
import al.xc.thirdparty.wechat.authorization.AccessTokenBean;
import al.xc.thirdparty.wechat.authorization.IWechatConfig;
import al.xc.thirdparty.wechat.authorization.SingleConfig;
import al.xc.thirdparty.wechat.authorization.WechatUtil;
import al.xc.data.model.wechat.GlobalSessionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Scope("singleton")
public class SessionRefreshTask {
    @Autowired
    private IWechatAuthorService authorService;

    private IWechatConfig config;

    /**
     * 初始化
     * @param config
     */
    public void initialize(IWechatConfig config) {
        this.config = config;
        for (SingleConfig info : config.listConfig()) {
            refreshTask(info);

        }
    }

    /**
     * 检查token刷新
     * @param info
     */
    private void refreshTask(SingleConfig info) {
        boolean refresh = true;
        try {
            GlobalSessionInfo sessionInfo = authorService.find(info.getAppid());
            if (null != sessionInfo && TimeUtils.diffTime(sessionInfo.getExpireTime(), new Date()) > 180000) {
                refresh = false;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (refresh) {
            try {
                dealRefresh(info);
                refresh = false;
            } catch (Exception ex) {
                refresh = true;
                ex.printStackTrace();
            }
        }
        SingleUtils.instance(DelayService.class).addQueue(()-> {
            refreshTask(info);
        }, refresh ? 5000 : 6000 * 3);
    }

    /**
     * 刷新token
     * @param info
     * @throws Exception
     */
    private void dealRefresh(SingleConfig info) throws Exception {
        WechatUtil util = new WechatUtil(config, info.getAppid());
        AccessTokenBean bean = util.globalSessionKey();
        authorService.insert(info.getAppid(), bean.getAccess_token(), bean.getExpires_in());
    }
}
